package osm;
     
     
     
import geocoding.Converter;
import geocoding.CustomNodes;
import geocoding.DistanceCalculator;
import graph.ALGOBuslineEdge;
import graph.ALGOGraph;
import graph.ALGOPlacemarkNode;
import graph.AStarGraph;
import graph.SearchableGraph;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;

import org.xmlpull.v1.XmlPullParserException;

import urnav.example.com.R;
import urnav.example.com.URNavActivity;
import android.app.Activity;
import android.content.res.XmlResourceParser;
import android.util.Log;

import com.keithpower.gekmlib.Placemark;
import com.keithpower.gekmlib.Point;



//Reads nodes and ways from OSM- files. Is replacement for MapReader- Class. Models OSM- Nodes into ALGOPlacemarkNodes and Ways into ALGOEdges. 
//Implemented with XMLResourceParser and therefore not very elegant, could be done with SAX. 
//All <node> tags have to be before all <way> tags in the OSM- file, which is obviously the case with files generated with JOSM.

     
     
     
    public class OsmReader extends Activity{
    	
    	private double minLat = Double.MAX_VALUE;
    	private double maxLat = Double.MIN_VALUE;
    	private double minLng = Double.MAX_VALUE;
    	private double maxLng = Double.MIN_VALUE;
    	public String motorwayName;
    	Converter myConverter=new Converter();
    	CustomNodes mycN=new CustomNodes();
    	ArrayList <Integer> refList = new ArrayList <Integer> ();
    	String TAG = "URNav";
    	String currentNode; 
     
    
    			public ALGOGraph readXml(){
            	int count = 0;
            	Hashtable<Integer,ALGOPlacemarkNode> stops = new Hashtable<Integer,ALGOPlacemarkNode>();
            	SearchableGraph map = new AStarGraph();

            	
            	try
     
                    {
     
//                    		Initialize the XMLResourceParser
     
                            XmlResourceParser xrp = URNavActivity.actVar.getResources().getXml(R.xml.unix);
     
                            while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
                            	
 
                                    if (xrp.getEventType() == XmlResourceParser.START_TAG) {
     
//                                    		Reads the attributes of <node>s and models them as ALGOPlacemarkNodes

     
                                        if (xrp.getName().equals("node")) {
                                        	
                                        	String s = xrp.getAttributeValue(null, "action");
                                        	if ((s != null ) | (s != "delete")) {
                                        	

                                                    String osm_id = xrp.getAttributeValue(null, "id");
                                        			double lat = Double.valueOf(xrp.getAttributeValue(null, "lat"));
                                        			double lng = Double.valueOf(xrp.getAttributeValue(null, "lon"));
                                        			ALGOPlacemarkNode node;
                                        			
                                        			if ((node = map.findNode(osm_id)) == null) {
                                        				Point p = new Point();
                                        				Placemark pm = new Placemark();
                                        				

                                        				if (lat < minLat) minLat = lat;
                                        				if (lat > maxLat) maxLat = lat;

                                        				if (lng < minLng) minLng = lng;
                                        				if (lng > maxLng) maxLng = lng;
                                        				
                                        				p.setNumericalCoordinates(new double[]{lat, lng, 0.0});
                                        				pm.addPoint(p);
                                        				pm.setName(osm_id);
                                        				
                                        				
                                        				node = new ALGOPlacemarkNode(count, pm);
                                        			
                                        			

                                        				map.addNode(node);
                                        				stops.put(new Integer(count), node);
//                                        				Log.i(TAG, "Added node");
//                                        				Log.i(TAG, node.toString() + count);
                                        				
//                                        				myConverter.convert(lat,lng,count,name);
                                        				addNode(lat,lng,osm_id,count);
                                        		
                                        				count++;
//                                        				xrp.next();
                                        			}
                                        	}
                                        			
                                        			
                                        			
                                        				xrp.next();
                                        			
     
     
                                            	}
                                    	  
                                      
                                            
                                            if (xrp.getName().equals("way") && (xrp.getEventType() == XmlResourceParser.START_TAG)) {
                                            	boolean building=false; 

                                            	xrp.next();
                                            	
//                                          Reads one <way> at a time, adds it's <nd>s to a list, then models the edges between the <nd>s as ALGOEdges
                                            
                                            while (!(xrp.getName().equals("way"))){
                                            	if (xrp.getName().equals("nd")  && (xrp.getEventType() == XmlResourceParser.START_TAG)) {                                         
                                                                                      
                                            		refList.add(Integer.parseInt((xrp.getAttributeValue(null, "ref"))));

                                            		xrp.next();
                                            	
                                            	}
                                            	if (xrp.getName().equals("tag")  && (xrp.getEventType() == XmlResourceParser.START_TAG)) {
                                            		if ((xrp.getAttributeValue(null, "k")).equals("building")) {
                                            			refList.clear();
//                                            			building=true; 
                                            		}
                                            		
                                            	}
                                            	
                                            	xrp.next();

                                            	}
                                            
//                                            if (building==false) {
                                            for (int i=0; i< refList.size()-1; i++){
                                            int startNum;
                                            int endNum;
                                            startNum=mycN.getPosition((refList.get(i)).toString());
                                            endNum=mycN.getPosition((refList.get(i+1)).toString());

                                    		ALGOPlacemarkNode pv = stops.get(new Integer(startNum));
                                    		ALGOPlacemarkNode pn = stops.get(new Integer(endNum));

//                                    		Log.i(TAG, "Edge from: " + getNodes().getOsm_id(startNum));
//                                    		Log.i(TAG, "to: " + getNodes().getOsm_id(endNum));

                                    		double costs = DistanceCalculator.getDistance(pv.getValue().getPoint().getNumericalCoordinates(), pn.getValue().getPoint().getNumericalCoordinates());
                                			map.addEdge(new ALGOBuslineEdge(pv.getNodeID(), pn.getNodeID(), costs));
                                			map.addEdge(new ALGOBuslineEdge(pn.getNodeID(), pv.getNodeID(), costs));
//                                            }
                                           }
                                            refList.clear();
//                                            xrp.next();
                                            	
                                          	  
                                          	 
     
                                            }
     
                                    } else if (xrp.getEventType() == XmlResourceParser.END_TAG) {
     
                                            ;
     
                                    } else if (xrp.getEventType() == XmlResourceParser.TEXT) {
     

     
                                    }
     
                                    xrp.next();
     
                            }
     
                            xrp.close();
     
     
     
                    } catch (XmlPullParserException xppe) {
     
                            Log.e(TAG, "Failure of .getEventType or .next, probably bad file format");
     
                            xppe.toString();
     
                    } catch (IOException ioe) {
     
                            Log.e(TAG, "Unable to read resource file");
     
                            ioe.printStackTrace();
     
                    }
     
   
     
        
     return map;
            
     
    }
        	public double getMinLat() {
        		return minLat;
        	}
        	
        	public double getMaxLat() {
        		return maxLat;
        	}
        	
        	public double getMinLng() {
        		return minLng;
        	}
        	
        	public double getMaxLng() {
        		return maxLng;

        	}

        	
//        	Adds nodes to the respective arraylists in CustomNodes     
        	public void addNode(double lati, double longi,String osm_id,int count){

//        	Setting default values to avoid OutOfBounds Errors
        		
        	mycN.setOsmID(count, osm_id);
        	mycN.setDlati(count, lati);
        	mycN.setDlongi(count, longi);
        	mycN.addLmtitle(count);
        	mycN.addHas_description(count, false);
        	mycN.addIs_uni_landmark(count,  false);
        	mycN.addHas_tags(count,  false);
        	mycN.addDist_landmark();
        	mycN.addHas_landmark();
        	mycN.addSilent(count);
        	mycN.addHas_tag_from_lm();
        	mycN.addLmrank();
        	
        	
        	}
        	
        	public void readTags(){
    	     
        		  try
                  
                  {
   
//                  		Initialize the XMLResourceParser
   
                          XmlResourceParser xrp = URNavActivity.actVar.getResources().getXml(R.xml.t2);
   
                          while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
                          	
          

   
                                  if (xrp.getEventType() == XmlResourceParser.START_TAG) {
   
//                                  		Reads the attributes of <node>s and models them as ALGOPlacemarkNodes

   
                                      if (xrp.getName().equals("node")) {
    
                                                  
                                                  String osm_id = xrp.getAttributeValue(null, "id");

//                                      			Log.i(TAG,"Node ID: " + osm_id);
                                      				
                                      			}
                                      
                          			if (xrp.getName().equals("tag")) {
                          			String v=xrp.getAttributeValue(null, "v");
                          			
//                          			Log.i(TAG, "Tag v" + v);
//                          			int nodeID=getNodes().getPosition(currentNode);
//                          			getNodes().is_uni_einrichtung.set(nodeID, true);
                          			
                          			
                              
//                              xrp.next();
                          			}
                                      			
                                      			
                                      				xrp.next();
                                      			
   
   
                                          	


                                          
//                                  	  xrp.next();
                                  	  

   
                                  } else if (xrp.getEventType() == XmlResourceParser.END_TAG) {
   
                                          ;
   
                                  } else if (xrp.getEventType() == XmlResourceParser.TEXT) {
   

   
                                  }
   
                                  xrp.next();
   
                          }
   
                          xrp.close();
 
 
                } catch (XmlPullParserException xppe) {
 
                        Log.e(TAG, "Failure of .getEventType or .next, probably bad file format");
 
                        xppe.toString();
 
                } catch (IOException ioe) {
 
                        Log.e(TAG, "Unable to read resource file");
 
                        ioe.printStackTrace();
 
                }
        
 
}
        		
        	
        	
        	public CustomNodes getNodes(){
        		return mycN;
        	}
    }
